# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：曾令为
#公司：https://blog.csdn.net/sinat_37967865
#文件：postQDZJ.py
#日期：2019-03-11
#备注：由于对有些渠道对同一客户10分钟内只能1次进件，为了性能测试的大并发量，必须每次进件传入的身份证都不相同
#流程：1.get_idCard函数通过id获取指定数量的身份证（另外拿到了批量身份证存入到了数据库）存放到一个列表；
      2.将身份证号作为参数传入到不同渠道的进件json报文，组合后存入到列表中；
      3.创建多线程，将进件的json报文当成多线程参数传入到进件函数post()，这样能够确保线程启动非常快。
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import pymysql
import requests
import copy
import time
import threading
import random
from interfacetest.baseset.qdzjmsloan_api import API_QDZJ
from pycacho.cachobase.logger import Logger

logger = Logger("postQDZJ").get_log()


class qdzjInfo(object):
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
            'content-Type': 'application/json'
        }
        self.api = 'https://test.coo.msxiaodai.com/msloan/api'    # http://dev.coo.msxiaodai.com/msloan/api
        self.db = pymysql.connect(
            host="10.16.20.182",
            #host="10.16.20.190",     # 开发环境
            user="dev",              # 测试：dev   开发：root
            password="dev",          # 测试：dev   开发：123456
            port=3306,
            use_unicode=True,
            charset="utf8",
            database="qdzjmsloandb")
        self.cursor = self.db.cursor()

        self.hy_channel = 'BJHY'
        self.gf_channel = 'M008'  # 贵丰项目M008
        self.jrb_channel = 'M009'  # 佳融宝项目
        self.zh_channel = 'BJZH'
        self.ssr_channel = 'M012'  # 深盛融项目
        self.gh_channel = 'M015'  # 固赫智能项目项目
        self.qh_channel = 'M016'  # 前海微贷项目
        self.yk_channel = 'M017'  # 云科贷项目
        self.bd_channel = 'M018'  # 百多项目
        self.md_channel = 'M023'  # 马达项目
        self.cm_channel = 'M024'  # 昌淼项目
        self.xy_channel = 'M019'  # 小业金融项目
        self.fy_channel = 'M020'  # 阜阳昌盛项目
        self.wr_channel = 'M021'  # 微融（国通贷款）项目
        self.hr_channel = 'M022'  # 海融项目
        self.ly_channel = 'SDLY'
        self.ws_channel = 'WHZH'
        self.jq_channel = 'M301'  # 精确通道
        self.yf_channel = 'M302'  # 永发项目


    def get_idCard(self,min,max):
        sql = "select id_card from zeng_idCardInfo where No>=%s and No<=%s;" % (min,max)
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        #print(results)
        idCards = []
        for result in results:
            idCards.append(result[0])
        #print(idCards)
        return(idCards)


    def get_jsonData(self, t):
        # 可以通过更改渠道名称去测试具体渠道
        temp = '1'
        hy_channel = 'BJHY'
        gf_channel = temp + 'M008'
        jrb_channel = temp + 'M009'
        zh_channel = temp + 'BJZH'
        ssr_channel = temp + 'M012'
        gh_channel = temp + 'M015'
        qh_channel = temp + 'M016'
        yk_channel = temp + 'M017'          # 云科贷项目
        bd_channel = 'M018'         # 百多项目
        md_channel = temp + 'M023'          # 马达项目(百多子项目)
        cm_channel = temp + 'M024'           # 昌淼项目(百多子项目)
        xyy_channel = temp + 'M019y'        # 小业金融项目360天
        xym_channel = temp + 'M019m'        # 小业金融项目30天
        fy_channel = temp + 'M020'         # 阜阳昌盛项目
        wr_channel = temp + 'M021'         # 微融（国通贷款）项目
        hr_channel = 'M022'         # 海融项目
        jq_channel = temp + 'M301'         # 精确通道
        yf_channel = temp + 'M302'         # 永发项目


        hy_Api = copy.deepcopy(API_QDZJ[self.hy_channel])
        gf_Api = copy.deepcopy(API_QDZJ[self.gf_channel])
        jrb_Api = copy.deepcopy(API_QDZJ[self.jrb_channel])
        zh_Api = copy.deepcopy(API_QDZJ[self.zh_channel])
        ssr_Api = copy.deepcopy(API_QDZJ[self.ssr_channel])
        gh_Api = copy.deepcopy(API_QDZJ[self.gh_channel])
        qh_Api = copy.deepcopy(API_QDZJ[self.qh_channel])
        yk_Api = copy.deepcopy(API_QDZJ[self.yk_channel])
        bd_Api = copy.deepcopy(API_QDZJ[self.bd_channel])
        md_Api = copy.deepcopy(API_QDZJ[self.bd_channel])
        cm_Api = copy.deepcopy(API_QDZJ[self.bd_channel])
        xyy_Api = copy.deepcopy(API_QDZJ[self.xy_channel+'y'])
        xym_Api = copy.deepcopy(API_QDZJ[self.xy_channel + 'm'])
        fy_Api = copy.deepcopy(API_QDZJ[self.fy_channel])
        wr_Api = copy.deepcopy(API_QDZJ[self.wr_channel])
        hr_Api = copy.deepcopy(API_QDZJ[self.hr_channel])
        jq_Api = copy.deepcopy(API_QDZJ[self.jq_channel])
        yf_Api = copy.deepcopy(API_QDZJ[self.yf_channel])

        data = []
        if hy_channel == self.hy_channel:
            qdzj_list = hy_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = hy_channel + str(t)
            qdzj_list['idCard'] = t
            # creditLimit = random.choice([500,1000,5000.99,1000.01,3000])
            # card['creditLimit'] = creditLimit
            # caseID["phone"] = '16000000000'
            # caseID["name"] = '16开头手机'
            data.append(hy_Api)

        if zh_channel == self.zh_channel:
            qdzj_list = zh_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = zh_channel + str(t)
            qdzj_list['idCard'] = t
            data.append(zh_Api)

        if gf_channel == self.gf_channel:
            qdzj_list = gf_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = gf_channel + str(t)
            qdzj_list['idCard'] = t
            data.append(gf_Api)

        if jrb_channel == self.jrb_channel:
            qdzj_list = jrb_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = jrb_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(jrb_Api)

        if ssr_channel == self.ssr_channel:
            qdzj_list = ssr_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = ssr_channel + str(10)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '452226199407166311'
            data.append(ssr_Api)

        if gh_channel == self.gh_channel:
            qdzj_list = gh_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = gh_channel + str(t)
            qdzj_list['idCard'] = t
            #creditLimit = random.choice([999.99,1000,5000.99,5001])
            #qdzj_list['creditLimit'] = creditLimit
            data.append(gh_Api)

        if qh_channel == self.qh_channel:
            qdzj_list = qh_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = qh_channel + str(t)
            qdzj_list['idCard'] = t
            data.append(qh_Api)

        if yk_channel == self.yk_channel:
            qdzj_list = yk_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = yk_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(yk_Api)

        if bd_channel == self.bd_channel:
            qdzj_list = bd_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = bd_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(bd_Api)

        if md_channel == self.md_channel:
            list = md_Api['service']['serviceHeader']
            list['channelCd'] = 'M023'
            qdzj_list = md_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = md_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(md_Api)

        if cm_channel == self.cm_channel:
            list = cm_Api['service']['serviceHeader']
            list['channelCd'] = 'M024'
            qdzj_list = cm_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = cm_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(cm_Api)

        if xyy_channel == self.xy_channel+'y':
            qdzj_list = xyy_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = xyy_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(xyy_Api)

        if xym_channel == self.xy_channel+'m':
            qdzj_list = xym_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = xym_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '452226199407166311'
            data.append(xym_Api)

        if fy_channel == self.fy_channel:
            qdzj_list = fy_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = fy_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(fy_Api)

        if wr_channel == self.wr_channel:
            qdzj_list = wr_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = wr_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(wr_Api)

        if hr_channel == self.hr_channel:
            qdzj_list = hr_Api['service']['serviceBody']['request']
            qdzj_list["caseId"] = hr_channel + str(t)
            qdzj_list['idCard'] = t
            #qdzj_list['idCard'] = '650102199012316847'
            data.append(hr_Api)

        if jq_channel == self.jq_channel:
            qdzj_list = jq_Api['service']['serviceBody']['request']
            qdzj_list["uniqueId"] = jq_channel + str(t)
            qdzj_list['idCardNum'] = t
            data.append(jq_Api)

        if yf_channel == self.yf_channel:
            qdzj_list = yf_Api['service']['serviceBody']['request']
            qdzj_list["uniqueId"] = '6' #yf_channel + str(t)
            qdzj_list['idCardNum'] = t
            data.append(yf_Api)

        return(data)


    def post(self,json_data):
        req1 = requests.post(self.api, json=json_data, headers=self.headers)
        logger.info("Post进件接口开始：")
        print(req1.text)


    def main(self):
        json_data = []                           # 所有发起的报文
        idCards = self.get_idCard(5,6)           # 算头算尾,控制进件数量
        for idCard in idCards:
            data_QDZJ = self.get_jsonData(idCard)      # 不同渠道
            for data_channel in data_QDZJ:
                json_data.append(data_channel)
        # print(json_data)

        # 将每个线程存储起来，同时跑增加速度
        threads = []
        for data in json_data:
            # print(data)
            t = threading.Thread(target=self.post, args=(data,))
            threads.append(t)

        # 设置等待时间,发起线程
        is_started = threading.Event()
        t1 = time.time()
        for t in threads:
            t.start()

        for t in threads:
            t.join()
            is_started.wait(timeout=0.5)  # 1秒钟跑2个案件

        logger.info("总共耗时：%.2f秒 ", time.time() - t1)


if __name__ == '__main__':
    order = qdzjInfo()
    order.main()
    #order.get_idCard()
